import {
  Controller,
  Fields,
  File,
  Get,
  Inject,
  Post,
} from '@midwayjs/decorator';
import { Context } from '@midwayjs/koa';
import type { UploadFileInfo } from '@midwayjs/upload';
import { Validate } from '@midwayjs/validate';
import { DeployOptionDto } from '../dto/DeployOptionDto';
// import * as StreamZip from 'node-stream-zip';
import { dirname, join } from 'path';
import { mkdir } from 'fs/promises';
// import { ResponseError } from '../error/response_error';

@Controller('/')
export class HomeController {
  @Inject()
  ctx: Context;

  @Get('/')
  async home(): Promise<string> {
    return 'Hello Midwayjs!';
  }

  @Get('/login')
  async login() {
    return this.ctx.render('login.html');
  }

  // @Get('/deploy')
  // async deploy(): Promise<string> {
  //   throw new ResponseError(200, '错误');
  // }

  /**
   * 通过推送压缩文件，然后解压并放到指定目录，实现自动化部署
   * @returns
   */
  @Post('/deploy')
  @Validate({
    validationOptions: {
      allowUnknown: true,
    },
  })
  async deploy(
    @File() file: UploadFileInfo<string>,
    @Fields() fields: DeployOptionDto
  ): Promise<string> {
    if (file == null) {
      this.ctx.status = 422;
      return '请上传部署文件';
    }
    await mkdir(join(dirname(file.data), fields.name));
    this.ctx.logger.info(dirname(file.data));
    // const zip = new StreamZip.async({ file: file.data });
    this.ctx.logger.info(fields);
    console.log(file);
    return 'SUCCESS';
  }

  @Get('/system_monitor')
  async systemMonitor(): Promise<string> {
    return 'SUCCESS';
  }
}
